<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="600px" :title="`${drawerProps.title}产品`">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>
      
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="drawerProps.row!.productCode" placeholder="请输入产品编码" clearable maxlength="50"></el-input>
      </el-form-item>
      
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="drawerProps.row!.productName" placeholder="请输入产品名称" clearable maxlength="100"></el-input>
      </el-form-item>
      
      <el-form-item label="产品型号" prop="model">
        <el-input v-model="drawerProps.row!.model" placeholder="例如：DRX-8000" clearable maxlength="50"></el-input>
      </el-form-item>
      
      <el-form-item label="产品类别" prop="category">
        <el-select v-model="drawerProps.row!.category" placeholder="请选择产品类别" clearable filterable style="width: 100%">
          <el-option label="电子部件" value="电子部件" />
          <el-option label="驱动器" value="驱动器" />
          <el-option label="机械零件" value="机械零件" />
          <el-option label="轴承" value="轴承" />
          <el-option label="传感器" value="传感器" />
          <el-option label="控制器" value="控制器" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="产品类型" prop="type">
        <el-select v-model="drawerProps.row!.type" placeholder="请选择产品类型" clearable @change="handleTypeChange" style="width: 100%">
          <el-option label="原材料" value="RAW_MATERIAL" />
          <el-option label="半成品" value="SEMI_FINISHED" />
          <el-option label="成品" value="FINISHED" />
        </el-select>
        <div class="form-tip">
          <el-text size="small" type="info">原材料：生产用的基础材料；半成品：加工中的产品；成品：最终产品</el-text>
        </div>
      </el-form-item>
      
      <el-form-item label="产品规格" prop="specification">
        <el-input 
          v-model="drawerProps.row!.specification" 
          type="textarea" 
          :rows="3"
          placeholder="例如：8x 速率, SATA 接口、16x 速率, USB3.0接口" 
          maxlength="200"
          show-word-limit
        ></el-input>
      </el-form-item>
      
      <el-form-item label="产品版本" prop="version">
        <el-input v-model="drawerProps.row!.version" placeholder="例如：V1.0" clearable maxlength="20"></el-input>
      </el-form-item>
      
      <el-form-item label="计量单位" prop="unit">
        <el-select v-model="drawerProps.row!.unit" placeholder="请选择计量单位" clearable filterable style="width: 100%">
          <el-option
            v-for="unit in unitOptions"
            :key="unit.id"
            :label="`${unit.unitName}(${unit.unitSymbol || unit.unitCode})`"
            :value="unit.unitCode"
          />
        </el-select>
      </el-form-item>

      <!-- BOM清单 -->
      <el-divider content-position="left">BOM清单</el-divider>
      
      <div v-if="showBomSection">
        <el-form-item label="BOM版本" prop="bom.bomVersion">
          <el-input v-model="drawerProps.row!.bom.bomVersion" placeholder="请输入BOM版本" clearable></el-input>
        </el-form-item>
        
        <el-form-item label="BOM类型" prop="bom.bomType">
          <el-select v-model="drawerProps.row!.bom.bomType" placeholder="请选择BOM类型" clearable style="width: 100%">
            <el-option label="设计BOM" value="设计BOM" />
            <el-option label="工艺BOM" value="工艺BOM" />
            <el-option label="装配BOM" value="装配BOM" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="BOM状态" prop="bom.status">
          <el-select v-model="drawerProps.row!.bom.status" placeholder="请选择BOM状态" clearable style="width: 100%">
            <el-option label="启用" value="启用" />
            <el-option label="停用" value="停用" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="BOM来源" prop="bom.source">
          <el-select v-model="drawerProps.row!.bom.source" placeholder="请选择BOM来源" clearable style="width: 100%">
            <el-option label="ERP同步" value="ERP同步" />
            <el-option label="MES内建" value="MES内建" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="生效时间" prop="bom.effectiveDate">
          <el-date-picker
            v-model="drawerProps.row!.bom.effectiveDate"
            type="datetime"
            placeholder="请选择生效时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="失效时间" prop="bom.expiredDate">
          <el-date-picker
            v-model="drawerProps.row!.bom.expiredDate"
            type="datetime"
            placeholder="请选择失效时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="物料清单">
          <div class="bom-materials">
            <div class="materials-header">
              <el-button type="primary" size="small" @click="addBomItem">添加物料</el-button>
            </div>
            
            <el-table :data="drawerProps.row!.bom.items" border style="width: 100%; margin-top: 10px;">
              <el-table-column prop="materialCode" label="物料编码" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.materialCode" placeholder="物料编码" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="materialName" label="物料名称" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.materialName" placeholder="物料名称" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" :min="1" :precision="0" size="small" style="width: 100%"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="100">
                <template #default="scope">
                  <el-select v-model="scope.row.unit" placeholder="单位" size="small" style="width: 100%">
                    <el-option
                      v-for="unit in unitOptions"
                      :key="unit.id"
                      :label="unit.unitCode"
                      :value="unit.unitCode"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="备注" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeBomItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </div>
      
      <div v-else>
        <el-text type="info">原材料无需配置BOM清单</el-text>
      </div>

      <!-- 查看模式下的额外信息 -->
      <template v-if="drawerProps.isView">
        <el-divider content-position="left">状态信息</el-divider>
        
        <el-form-item label="产品状态" prop="status">
          <el-tag :type="getStatusType(drawerProps.row!.status)">{{ getStatusText(drawerProps.row!.status) }}</el-tag>
        </el-form-item>
        
        <el-form-item label="工艺路线ID" prop="routeId" v-if="drawerProps.row!.routeId">
          <el-input v-model="drawerProps.row!.routeId" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="创建人" prop="createdBy" v-if="drawerProps.row!.createdBy">
          <el-input v-model="drawerProps.row!.createdBy" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="创建时间" prop="createdTime" v-if="drawerProps.row!.createdTime">
          <el-input v-model="drawerProps.row!.createdTime" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="更新人" prop="updatedBy" v-if="drawerProps.row!.updatedBy">
          <el-input v-model="drawerProps.row!.updatedBy" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="更新时间" prop="updatedTime" v-if="drawerProps.row!.updatedTime">
          <el-input v-model="drawerProps.row!.updatedTime" disabled></el-input>
        </el-form-item>
      </template>
    </el-form>
    
    <template #footer>
      <div class="drawer-button-box">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ProductForm">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Product, createProduct, updateProduct } from "@/api/modules/product";
import { getAllEnabledUnits } from "@/api/modules/unitManage";
import { UnitManage } from "@/api/interface";

const rules = reactive({
  productCode: [{ required: true, message: "请输入产品编码", trigger: "blur" }],
  productName: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  model: [{ required: true, message: "请输入产品型号", trigger: "blur" }],
  category: [{ required: true, message: "请选择产品类别", trigger: "change" }],
  type: [{ required: true, message: "请选择产品类型", trigger: "change" }],
  specification: [{ required: true, message: "请输入产品规格", trigger: "blur" }],
  version: [{ required: true, message: "请输入产品版本", trigger: "blur" }],
  unit: [{ required: true, message: "请选择计量单位", trigger: "change" }],
  "bom.bomVersion": [{ required: true, message: "请输入BOM版本", trigger: "blur" }],
  "bom.bomType": [{ required: true, message: "请选择BOM类型", trigger: "change" }],
  "bom.status": [{ required: true, message: "请选择BOM状态", trigger: "change" }],
  "bom.source": [{ required: true, message: "请选择BOM来源", trigger: "change" }],
  "bom.items": [
    { 
      type: "array", 
      min: 1, 
      message: "成品和半成品必须至少包含一条物料记录", 
      trigger: "change" 
    }
  ]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Product.ProductListItem>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 单位选项
const unitOptions = ref<UnitManage.ResUnitList[]>([]);

// 是否显示BOM部分
const showBomSection = computed(() => {
  return drawerProps.value.row.type === 'SEMI_FINISHED' || drawerProps.value.row.type === 'FINISHED';
});

// 获取单位选项
const getUnitOptions = async () => {
  try {
    const { data } = await getAllEnabledUnits();
    unitOptions.value = data;
  } catch (error) {
    console.error("获取单位列表失败:", error);
  }
};

// 产品类型变化处理
const handleTypeChange = (type: string) => {
  // 根据产品类型设置默认单位
  if (type === 'RAW_MATERIAL') {
    // 原材料清空BOM
    drawerProps.value.row.bom = undefined;
  } else {
    // 半成品/成品设置默认单位为"件"，并初始化BOM
    if (!drawerProps.value.row.unit) {
      drawerProps.value.row.unit = 'PCS';
    }
    if (!drawerProps.value.row.bom) {
      drawerProps.value.row.bom = {
        bomVersion: 'V1.0',
        bomType: '设计BOM',
        status: '启用',
        source: 'MES内建',
        effectiveDate: new Date().toISOString(),
        expiredDate: '',
        items: []
      };
    }
  }
};

// 添加BOM物料项
const addBomItem = () => {
  if (!drawerProps.value.row.bom) {
    drawerProps.value.row.bom = {
      bomVersion: 'V1.0',
      bomType: '设计BOM',
      status: '启用',
      source: 'MES内建',
      effectiveDate: new Date().toISOString(),
      expiredDate: '',
      items: []
    };
  }
  
  drawerProps.value.row.bom.items.push({
    materialCode: '',
    materialName: '',
    quantity: 1,
    unit: 'PCS',
    remark: ''
  });
};

// 删除BOM物料项
const removeBomItem = (index: number) => {
  if (drawerProps.value.row.bom?.items) {
    drawerProps.value.row.bom.items.splice(index, 1);
  }
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "info",
    enabled: "success",
    disabled: "warning",
    approved: "primary",
    rejected: "danger",
    deleted: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "已创建",
    enabled: "已启用",
    disabled: "已禁用",
    approved: "已审核",
    rejected: "已驳回",
    deleted: "已删除"
  };
  return statusMap[status] || status;
};

// 接收父组件传过来的参数
const open = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  
  // 设置默认值
  if (drawerProps.value.title === "新增") {
    if (!drawerProps.value.row.version) {
      drawerProps.value.row.version = "V1.0";
    }
    if (!drawerProps.value.row.unit) {
      drawerProps.value.row.unit = "PCS";
    }
  }
  
  // 确保BOM结构存在
  if (showBomSection.value && !drawerProps.value.row.bom) {
    drawerProps.value.row.bom = {
      bomVersion: 'V1.0',
      bomType: '设计BOM',
      status: '启用',
      source: 'MES内建',
      effectiveDate: new Date().toISOString(),
      expiredDate: '',
      items: []
    };
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    
    // 验证BOM数据
    if (showBomSection.value && drawerProps.value.row.bom) {
      const bom = drawerProps.value.row.bom;
      
      // 验证BOM基本信息
      if (!bom.bomVersion || !bom.bomType || !bom.status || !bom.source) {
        ElMessage.error("请完善BOM基本信息");
        return;
      }
      
      // 验证BOM物料项
      if (!bom.items || bom.items.length === 0) {
        ElMessage.error("成品和半成品必须至少包含一条物料记录");
        return;
      }
      
      // 验证每个物料项的必填字段
      for (let i = 0; i < bom.items.length; i++) {
        const item = bom.items[i];
        if (!item.materialCode || !item.materialName || !item.quantity || !item.unit) {
          ElMessage.error(`第${i + 1}行物料信息不完整，请检查物料编码、名称、数量和单位`);
          return;
        }
        if (item.quantity <= 0) {
          ElMessage.error(`第${i + 1}行物料数量必须大于0`);
          return;
        }
      }
    }
    
    try {
      const isEdit = !!drawerProps.value.row.id;
      
      if (isEdit) {
        // 编辑产品 - 根据实际API调整参数
        const params = {
          productName: drawerProps.value.row.productName!,
          model: drawerProps.value.row.model!,
          category: drawerProps.value.row.category!,
          type: drawerProps.value.row.type!,
          specification: drawerProps.value.row.specification!,
          version: drawerProps.value.row.version!,
          unit: drawerProps.value.row.unit!,
          bom: drawerProps.value.row.bom
        };
        await updateProduct(drawerProps.value.row.id!, params);
        ElMessage.success("产品更新成功！");
      } else {
        // 新增产品 - 按照CreateProductRequest结构
        const params = {
          productCode: drawerProps.value.row.productCode!,
          productName: drawerProps.value.row.productName!,
          model: drawerProps.value.row.model!,
          category: drawerProps.value.row.category!,
          type: drawerProps.value.row.type!,
          specification: drawerProps.value.row.specification!,
          version: drawerProps.value.row.version!,
          unit: drawerProps.value.row.unit!,
          bom: drawerProps.value.row.bom
        };
        await createProduct(params);
        ElMessage.success("产品创建成功！");
      }

      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.error("提交失败:", error);
      ElMessage.error("操作失败！");
    }
  });
};

// 页面加载时获取单位选项
onMounted(() => {
  getUnitOptions();
});

defineExpose({
  open
});
</script>

<style scoped>
.drawer-button-box {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.form-tip {
  margin-top: 5px;
  
  .el-text {
    line-height: 1.2;
  }
}

.bom-materials {
  .materials-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .el-table {
    margin-top: 10px;
  }
}

.el-divider {
  margin: 20px 0;
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-table .el-input),
:deep(.el-table .el-select),
:deep(.el-table .el-input-number) {
  width: 100%;
}
</style>